﻿using FrameworkCore.Extensions;
using FrameworkCore.Modules.Startups;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.ComponentModel.DataAnnotations;

namespace AiBLSmartEdu.Module.ExceptionHandle;

public partial class AiBLSmartEduStartup : IAiBLSmartEduStartup
{
    public int Order => 20;

    public void Configure(IApplicationBuilder application)
    {
        application.UseExceptionHandler();
    }

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        //拦截参数校验异常
        services.Configure<ApiBehaviorOptions>(options => //请求参数校验
        {
            options.InvalidModelStateResponseFactory = actionContext =>
            {
                var errors = actionContext.ModelState
                   .Where(e => e.Value?.Errors.Count > 0)
                   .Select(e => e.Value?.Errors.First().ErrorMessage)
                   .ToList();
                throw new ValidationException(errors.Join("|"));
            };
        });

        services.AddExceptionHandler<ExceptionHandler>();
        services.AddProblemDetails();
    }
}